<template>
  <el-dialog :visible.sync="dialog" width="1000px" @closed="closeDialog">
    <div class="wxConcat">
      <div class="concat-left-tree">
        <div class="top-wrapper wrapper-flex">
          <el-input placeholder="输入员工名称" size="mini" v-model="keyword"/>
          <el-button size="mini" type="primary" @click="searchConcat">搜 索</el-button>
        </div>
        <div class="overflow_y">
          <el-tree ref="concatTree" :data="data"
                   @node-click="choiceDept"
                   :props="{children:'children',label:'name'}"
                   node-key="id">
          </el-tree>
        </div>
      </div>
      <div class="concat-choice">
        <div class="concat-middle">
          <div class="top-wrapper middle-wrapper line-height">
            <div class="text-center">可选人员</div>
            <wx-link class="select-all" @click.native="selectAll" v-if="!single">全选</wx-link>
          </div>
          <div class="overflow_y">
            <div class="item-wrapper" v-for="(c,i) in unselected" :key="i">
              <div style="flex:1;" @click="addChoice(c,i)">
                {{ c.name }}
              </div>
              <div>
                <el-checkbox v-model="c.check" @change="addChoiceBox(c,i)"/>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="concat-right">
        <div class="top-wrapper text-center" :class="{'line-height':!single}">
          <div>
            <span>已选人员</span>
            <span class="al-tips-text-org" v-if="single">最多可选1人</span>
          </div>
        </div>
        <div class="overflow_y">
          <div class="item-wrapper" v-for="(c,i) in choice" :key="i">
            <div>{{ c.name }}</div>
            <wx-link style="font-size:12px" @click.native="delChoice(c,i)">删除</wx-link>
          </div>
        </div>
      </div>
    </div>

    <div class="dialog-concat-footer">
      <div class="dialog-refresh">
        <span>更新企业通讯录数据</span>
        <i class="el-icon-refresh-right" @click="syncQiyeTxl"/>
      </div>
      <div class="dialog-footer">
        <el-button @click="dialogCancel">取 消</el-button>
        <el-button type="primary" @click="dialogSure">确 定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import WxLink from "@/components/wxqy/wxLink/wxLink";
import {updateQiyeTxl} from "@/api/wxqy/qiyeConfig";
import {teamDepts, teamUsers} from '@/api/wxqy/Search'

/**
 * 确定回调方法：@sure
 */
export default {
  name: "wxConcat",
  components: {WxLink},
  props: {
    show: {
      default: false
    },
    choiceConcats: {
      type: Array,
      default: () => []
    },
    single: { //单选
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      dialog: this.show,
      data: null,
      unselected: [],
      choice: [],
      keyword: null
    }
  },
  watch: {
    show: function (v) {
      this.dialog = v
      this.isCancel = false
      if (!this.data){
        this.loadData()
      }
    },
    choiceConcats: {
      immediate: true,
      handler(v) {
        if (v && v.length) {
          this.choice = this.choiceConcats.map(t => t)
          if (!this.show){
            this.addCheck()
          }
        }
      }
    }
  },
  methods: {
    addChoiceBox(row, index) {
      row.check = !row.check
      this.addChoice(row, index);
    },
    addChoice(row, index) {
      if (!this.choice) this.choice = []
      if (row.check) {
        this.choice = this.choice.filter(c => c.id !== row.id)
      } else {
        if (this.single && this.choice.length) {
          this.unselected.map(u => u.check = false)
          this.choice.splice(0, 1, row)
        } else {
          this.choice.push({id: row.id, name: row.name})
        }
      }
      this.unselected[index].check = !(row.check || false)
    },
    delChoice(row, index) {
      this.choice.splice(index, 1)
      for (const u of this.unselected) {
        if (u.id === row.id) {
          u.check = false
        }
      }
    },
    closeDialog() {
      this.dialog = false
      this.$emit('update:show', false)
      if (this.isCancel) { // 取消时，还原数据
        this.choice = this.choiceConcats && this.choiceConcats.length
          ? this.choiceConcats.map(t => t)
          : []
        let choices = this.choiceConcats.map(concat => concat.id)
        this.unselected.map(un => un.check = choices.includes(un.id))
        this.isCancel = false
      }
    },
    dialogCancel() {
      this.dialog = false
      this.isCancel = true
    },
    dialogSure() {
      this.$emit('sure', this.choice)
      this.closeDialog()
    },
    selectAll() {
      let count = this.unselected.filter(t => !t.check).length
      if (count > 0) {
        this.choiceAll()
      } else {
        this.delUnselectedData()
      }
    },
    choiceAll() {
      if (!this.choice) this.choice = []
      let choicedList = this.choice.map(m => m.id)
      for (const u of this.unselected) {
        u.check = true
        if (!choicedList.includes(u.id)) {
          this.choice.push({id: u.id, name: u.name})
          choicedList.push(u.id)
        }
      }
    },
    delUnselectedData() {
      let delChoice = []
      for (const u of this.unselected) {
        u.check = false
        delChoice.push(u.id)
      }
      this.choice = this.choice.filter(t => !delChoice.includes(t.id))
    },
    depts(deptId) {
      teamDepts({deptId: deptId}).then(e => {
        let data = e.data
        let min = 99999
        for (let i = 0; i < data.length; i++) {
          min = Math.min(data[i].parentId, min)
        }
        this.data = this.treeDir(data, min)
      })
    },
    users(name, deptId) {
      let params = {
        deptId: deptId ? deptId : 0,
        name: name ? name : ''
      }
      teamUsers(params).then(e => {
        this.unselected = e.data
        this.addCheck()
      })
    },
    async loadData() {
      await this.depts(0)
      await this.users('')
    },
    treeDir(data, parentId) {
      let departments = data.filter(d => d.parentId === parentId).map(d => {
        return {
          id: d.id,
          name: d.name,
          children: null
        }
      })
      for (let department of departments) {
        department.children = this.treeDir(data, department.id)
      }
      return departments
    },
    searchConcat() {
      let rootNodes = this.$refs.concatTree.root.childNodes
      if (rootNodes.length) {
        for (let node of rootNodes) {
          node.expanded = false
        }
      }
    },
    recursionFindDeptIds(depts) {
      let ids = []
      for (let i = 0; i < depts.length; i++) {
        ids.push(depts[i].id)
        if (depts[i].children) {
          ids = ids.concat(this.recursionFindDeptIds(depts[i].children))
        }
      }
      return ids
    },
    addCheck() {
      let choice = this.choice.map(c => c.id)
      if (choice.length) {
        this.unselected.map(s => {
          s.check = choice.includes(s.id)
          return s
        })
      }
    },
    choiceDept(e1) {
      let ids = this.recursionFindDeptIds([e1])
      if (!this.cpUsers) {
        this.cpUsers = [...[], ...this.unselected]
      }
      this.unselected = []
      for (let i = 0; i < this.cpUsers.length; i++) {
        let d = this.cpUsers[i].depts.filter(d => ids.includes(d.id))
        if (d.length) {
          this.unselected.push(this.cpUsers[i])
        }
        delete this.cpUsers[i]['check']
      }
      this.addCheck()
    },
    syncQiyeTxl() {
      updateQiyeTxl()
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../assets/styles/common";

.el-dialog__header {
  padding: 0;
}

.wxConcat {
  height: 400px;
  @include flex-start;
  align-items: flex-start;

  .concat-left-tree,
  .concat-right, .concat-middle {
    width: 33%;
    height: calc(100% - 60px);
  }

  .concat-choice {
    height: 100%;
    width: 33%;
    border-right: 1px solid rgba(0, 0, 0, .1);
    border-left: 1px solid rgba(0, 0, 0, .1);
  }

  .top-wrapper {
    font-weight: 500;
    font-size: 14px;
    margin: 0 10px 10px 0;
    height: 40px;
  }

  .concat-middle {
    width: 100%;

    .middle-wrapper {
      position: relative;

      .select-all {
        position: absolute;
        right: 0;
        top: 0;
      }
    }
  }

  .line-height {
    line-height: 40px;
  }

  .item-wrapper {
    @include flex-between;
    line-height: 40px;
    padding: 0 10px;
    color: #606266;
    font-size: 14px;
    font-weight: 500;
  }

  .wrapper-flex {
    @include flex-between;

    ::v-deep .el-input {
      margin-right: 10px;
    }
  }
}

.dialog-concat-footer {
  @include flex-between;
  margin: 10px 0;

  .dialog-refresh {
    align-items: center;
    display: flex;
    flex-direction: row;
    font-size: 12px;
    color: #676868;

    i {
      font-size: 18px;
      color: #00afff;
      margin-left: 5px;
      cursor: pointer;
    }
  }
}
</style>
